﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AssetFrame.BP;
using AssetFrame.Message;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SysFrame.BP;
using SysFrame.Message;

namespace AppServer.Controllers.Asset
{
    [Route("api/[controller]")]
    [ApiController]
    public class AssetA1Controller : SysControllerBase
    {
        // 资产数据
        // POST: api/AssetA1
        [HttpPost]
        public ActionResult<string> Post([FromBody] dynamic data)
        {
            string jsTimeStamp = data.jsTimeStamp;
            string Action = data.Action == null ? "Get" : data.Action;
            string rtstr = "";
            //得到列表
            if (Action == "Get")
            {
                rtstr = Get(data);
            }
            if (Action == "GetByQuery")
            {
                rtstr = GetByQuery(data);
            }
            if (Action == "GetSysAssetA2")
            {
                rtstr = GetSysAssetA2(data);
            }
            if (Action == "GetEditForm")
            {
                rtstr = GetEditForm(data);
            }
            if (Action == "GetNewAsset")
            {
                rtstr = GetNewAsset(data);
            }
            if (Action == "GetAssetA1Ddl")
            {
                rtstr = GetAssetA1Ddl(data);
            }
            if (Action == "Save")
            {
                rtstr = Save(data);
            }
            if (Action == "DeleteA1")
            {
                rtstr = DeleteA1(data);
            }
            if (Action == "AssetCopy")
            {
                rtstr = AssetCopy(data);
            }
            return rtstr;
        }

        #region 列表 查询
        /// <summary>
        /// 得到选择的值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Get(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            JObject search = JObject.FromObject(postdata["search"]);//查询
            MsQuery msq = new MsQuery();
            string str60s = search["str60s"].ToString();
            string pagequery = search["pagequery"].ToString();
            JArray assetquery = JArray.FromObject(search["assetquery"]);

            JObject sort = JObject.FromObject(postdata["sort"]);//排序
            string strorder = sort["strorder"].ToString();
            string ordertype = sort["ordertype"].ToString();
            msq.strquery += " and 1=1 ";
            //查询字符串
            if (pagequery != "")
            {
                //string tabname = item.SYS_ASSET_A1_60 + item.AUTOID;

                List<string> listCONCAT = new List<string>();

                List<Mssys_asset_a1> lsitfields = GetSysAssetA2();
                foreach (var item in lsitfields)
                {

                    if (string.IsNullOrEmpty(item.SYS_ASSET_A1_60)
                        && string.IsNullOrEmpty(item.SYS_ASSET_A1_70)
                        && string.IsNullOrEmpty(item.SYS_ASSET_A1_80))
                    {
                        listCONCAT.Add("a1." + item.SYS_ASSET_A1_160 + " like '%" + pagequery + "%'");
                    }
                    else
                    {
                        string tabname = item.SYS_ASSET_A1_60 + item.AUTOID;
                        listCONCAT.Add(tabname + "." + item.SYS_ASSET_A1_80 + " like '%" + pagequery + "%'");
                        foreach (var tabcol in item.SYS_ASSET_A1_100.Split(','))
                        {
                            if (tabcol != "")
                            {
                                listCONCAT.Add(tabname + "." + tabcol + " like '%" + pagequery + "%'");
                            }
                        }
                    }
                }
                msq.strquery += " and (" + string.Join(" or ", listCONCAT) + ")";
            }
            //资产分类
            if (str60s != "")
            {
                msq.strquery += " and  a1.ASSET_A1_60 IN ('" + string.Join("','", str60s.Split(',')) + "')";
            }
            if (assetquery.Count != 0)
            {
                msq.strquery += " and " + GetQueryByquerjs(assetquery);
            }
            msq.strorder = strorder;
            msq.ordertype = ordertype;
            return Get(msq);
        }


        /// <summary>
        /// 得到选择的值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string GetByQuery(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            JArray querydata = JArray.FromObject(postdata["querydata"]);
            MsQuery msq = new MsQuery();
            msq.strquery = " and " + GetQueryByquerjs(querydata);
            return Get(msq);
        }

        /// <summary>
        /// 得到选择的值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Get(MsQuery msq)
        {
            msq.strquery += " and 1=1 and (ASSET_A1_ISDEL is null or ASSET_A1_ISDEL!='1')";
            DataTable dt = new BLLasset_a1().Getasset_a1DataByQuery(msq);
            return JArray.FromObject(dt).ToString();
        }

        /// <summary>
        /// 得到资产列头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string GetSysAssetA2(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            List<Mssys_asset_a1> listsysa1 = new List<Mssys_asset_a1>();
            listsysa1 = GetSysAssetA2();
            return JArray.FromObject(listsysa1).ToString();
        }

        public static string GetQueryByquerjs(JArray querydata)
        {
            List<assetquery> listquery = (List<assetquery>)querydata.ToObject(typeof(List<assetquery>));
            List<string> querystr = new List<string>();
            foreach (var item in listquery)
            {
                StringBuilder sbquery = new StringBuilder();
                if (item.name.IndexOf(".") < 0)
                {
                    sbquery.Append(" a1.").Append(item.name).Append(" ");
                }
                switch (item.symbol)
                {
                    case "=":
                        sbquery.Append("=").Append(item.strvalue);
                        break;
                    case "!=":
                        sbquery = new StringBuilder();
                        sbquery.Append(" (a1.").Append(item.name).Append(" ");
                        sbquery.Append("!=").Append(item.strvalue);
                        sbquery.Append(" or ").Append(item.name).Append(" is null)");
                        break;
                    case ">":
                        sbquery.Append(">").Append(item.strvalue);
                        break;
                    case "<":
                        sbquery.Append("<").Append(item.strvalue);
                        break;
                    case ">=":
                        sbquery.Append(">=").Append(item.strvalue);
                        break;
                    case "<=":
                        sbquery.Append("<=").Append(item.strvalue);
                        break;
                    case "like":
                        sbquery.Append("like ").Append(item.strvalue);
                        break;
                    case "not like":
                        sbquery.Append("not like ").Append(item.strvalue);
                        break;
                    case "likestart":
                        sbquery.Append("like ").Append(item.strvalue);
                        break;
                    case "likeend":
                        sbquery.Append("like ").Append(item.strvalue);
                        break;
                    case "in":
                        sbquery.Append("in ").Append(item.strvalue);
                        break;
                    case "not in":
                        sbquery.Append("not in ").Append(item.strvalue);
                        break;
                    default:
                        break;
                }
                if (item.strvalue.Replace("'", "") != "")
                {
                    querystr.Add(sbquery.ToString());
                }
            }
            return string.Join(" and ", querystr);
        }


        /// <summary>
        /// 查询条件
        /// </summary>
        public class assetquery
        {
            private string _name;//字段名称
            private string _symbol;//运算符
            //[["=", "等于", 1, "", ""],
            //[">", "大于", 1, "", ""],
            //["<", "小于", 1, "", ""],
            //["like", "包含", 1, "", ""],
            //["not like", "不包含", 1, "", ""],
            //["likestart", "以...开头", 1, "", ""],
            //["likeend", "以...结束", 1, "", ""],
            //["in", "包含", 1, "", ""],
            //["not in", "不包含", 1, "", ""]];
            private List<string> _value;//值
            private string _strvalue;//值


            /// <summary>
            /// 值
            /// </summary>	
            public string strvalue
            {
                get { return _strvalue; }
                set { _strvalue = value; }
            }



            /// <summary>
            /// 值
            /// </summary>	
            public List<string> value
            {
                get { return _value; }
                set
                {
                    _value = value;
                    _strvalue = "'" + string.Join("','", _value) + "'";
                    if (_symbol == "like" || _symbol == "not like")
                    {
                        _strvalue = "'%" + string.Join("','", _value) + "%'";
                    }
                    if (_symbol == "likestart")
                    {
                        _strvalue = "'%" + string.Join("','", _value) + "'";
                    }
                    if (_symbol == "likeend")
                    {
                        _strvalue = "'" + string.Join("','", _value) + "%'";
                    }
                    if (_symbol == "in" || _symbol == "not in")
                    {
                        _strvalue = "('" + string.Join("','", _value) + "')";
                    }
                }
            }


            /// <summary>
            /// 运算符
            /// </summary>	
            public string symbol
            {
                get { return _symbol; }
                set { _symbol = value; }
            }


            /// <summary>
            /// 字段名称
            /// </summary>	
            public string name
            {
                get { return _name; }
                set { _name = value; }
            }

        }
        #endregion

        #region 编辑
        /// <summary>
        /// 绑定数据集合
        /// </summary>
        private JObject DataSource = null;

        /// <summary>
        /// 得到资产列头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string GetAssetA1Ddl(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            JObject sysasseta1 = JObject.FromObject(postdata["sysasseta1"]);
            Mssys_asset_a1 sysa1 = Mssys_asset_a1.parse(sysasseta1);
            DataSource = new JObject();

            //资产分类
            if (sysa1.SYS_ASSET_A1_60.ToUpper() == "ASSET_A2")
            {
                GetAssetA2();
                DataSource.Add("DataValueField", "ASSET_A2_AUTOID");
                DataSource.Add("DataTextField", "ASSET_A2_10");
                DataSource.Add("TreeLevelField", "ASSET_A2_PARENTID");
            }
            //品牌
            if (sysa1.SYS_ASSET_A1_60.ToUpper() == "ASSET_A3")
            {
                GetAssetA3();
                DataSource.Add("DataValueField", "ASSET_A3_AUTOID");
                DataSource.Add("DataTextField", "ASSET_A3_10");
            }
            //型号
            if (sysa1.SYS_ASSET_A1_60.ToUpper() == "ASSET_A4")
            {
                string a3id = "";
                if (postdata.ContainsKey("opt")) {
                    a3id = postdata["opt"].ToString();
                }
                GetAssetA4(a3id);
                DataSource.Add("DataValueField", "ASSET_A4_AUTOID");
                DataSource.Add("DataTextField", "ASSET_A4_10");
                DataSource.Add("TreeLevelField", "ASSET_A4_30");
                DataSource.Add("DisabledField", "canselect");
            }
            //存放地址配置
            if (sysa1.SYS_ASSET_A1_60.ToUpper() == "ASSET_A5")
            {
                GetAssetA5();
                DataSource.Add("DataValueField", "ASSET_A5_AUTOID");
                DataSource.Add("DataTextField", "ASSET_A5_10");
            }
            //部门
            if (sysa1.SYS_ASSET_A1_60.ToUpper() == "SYSTEM_2")
            {
                GetSystem2();
                DataSource.Add("DataValueField", "System_2_10");
                DataSource.Add("DataTextField", "System_2_30");
            }
            //字典
            if (sysa1.SYS_ASSET_A1_60 == "system_4")
            {
                GetSystem4(sysa1);
                DataSource.Add("DataValueField", sysa1.SYS_ASSET_A1_70);
                DataSource.Add("DataTextField", sysa1.SYS_ASSET_A1_80);
            }


            return DataSource.ToString();
        }

        /// <summary>
        /// 得到资产列头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string GetEditForm(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            List<Mssys_asset_a1> listms = new List<Mssys_asset_a1>();
            MsQuery msq = new MsQuery();
            msq.strquery += " and SYS_ASSET_A1_40='1'";
            msq.strquery += " and SYS_ASSET_A1_130='1'";
            msq.typecode1 = "asset";
            listms = new BLLsys_asset_a1().Getsys_asset_a1MsByQuery(msq);
            JArray group = new JArray();

            foreach (var item in listms)
            {
                //分组数据
                if (!group.ToList().Contains(item.SYS_ASSET_A1_140.ToString()))
                {
                    group.Add(item.SYS_ASSET_A1_140.ToString());
                }
                //字典
                if (item.SYS_ASSET_A1_60 == "system_4")
                {
                    //GetSystem4(item);
                }
            }
            //GetAssetA2();
            //GetAssetA3();
            //GetAssetA4();
            //GetAssetA5();
            //GetSystem2();
            JObject jo = new JObject();
            jo.Add("group", group);
            jo.Add("fields", JArray.FromObject(listms));
            //jo.Add("DataSource", DataSource);
            return jo.ToString();
        }

       /// <summary>
       /// 得到最大编号
       /// </summary>
       /// <returns></returns>
        public string GetNewAsset(dynamic data)
        {
            JObject resdata = new JObject();
            resdata.Add("ASSET_A1_30", BLLasset_a1.GetMaxSysCode());
            resdata.Add("ASSET_A1_280", "005001");
            resdata.Add("strASSET_A1_280", new BLLsystem_4().Getsystem_4ByCode("005001").System_4_40);
            return resdata.ToString();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Save(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            Msasset_a1 ms1 = Msasset_a1.parse(postdata);
            ms1.ASSET_A1_MAKEFROM = "1";//1页面新增
            ms1.ASSET_A1_MAKETIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//新增时间
            ms1.ASSET_A1_ISDEL = "０";//有效
            ms1.typecode1 = "007001";
            string value = GetSession("LoginUser");
            Mssystem_1 lodeuser = Mssystem_1.parse(value);
            ms1.typecode2 = lodeuser.System_1_10.ToString();
            MsReturned rt = new BLLasset_a1().Saveasset_a1(ms1);
            return JObject.FromObject(rt).ToString();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string DeleteA1(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            JArray ids = JArray.FromObject(postdata["ids"]);
            MsReturned rt = new MsReturned();
            if (ids.Count != 0) {
                MsQuery msq = new MsQuery();
                msq.strquery += " and ASSET_A1_AUTOID in ('"+ string.Join("','",ids) + "')";
                rt = new BLLasset_a1().Deleteasset_a1ByQuery(msq);
            }
            return JObject.FromObject(rt).ToString();
        }
        /// <summary>
        /// 拆分
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string AssetCopy(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            string id = postdata["id"].ToString();
            MsReturned rt = new MsReturned();
            BLLasset_a1 bll = new BLLasset_a1();
            Msasset_a1 msa1 = bll.Getasset_a1MsByKey(id);
            //复制数量
            int nub = Convert.ToInt32(msa1.ASSET_A1_10) - 1;
            msa1.ASSET_A1_10 = 1;
            bll.Saveasset_a1(msa1);
            for (int i = 0; i < nub; i++)
            {
                Msasset_a1 newasset = msa1;
                newasset.ASSET_A1_30 = BLLasset_a1.GetMaxSysCode();
                newasset.ASSET_A1_10 = 1;
                newasset.ASSET_A1_AUTOID = 0;
                bll.Saveasset_a1(newasset);
            }
            rt.MsRbool = true;
            rt.strMS = "保存成功";
            return JObject.FromObject(rt).ToString();
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 资产分类配置
        /// </summary>
        private void GetSystem4(Mssys_asset_a1 item)
        {
            MsQuery msq = new MsQuery();
            msq.strquery += " and 1=1 ";
            msq.strquery += " and " + item.SYS_ASSET_A1_90.Replace("$tab$", "system_4");
            List<Mssystem_4> dt = new BLLsystem_4().Getsystem_4MsByQuery(msq);
            DataSource.Add("DataSource", JArray.FromObject(dt));
        }

        /// <summary>
        /// 资产分类配置
        /// </summary>
        private void GetAssetA2()
        {
            MsQuery msq = new MsQuery();
            msq.strquery += " and 1=1 ";
            DataTable dt = ((DataSet)new BLLasset_a2().Getasset_a2ByQuery(msq).data).Tables[0];
            DataSource.Add("DataSource", JArray.FromObject(dt));
        }
        /// <summary>
        /// 资产分类配置 可以多选的树菜单
        /// </summary>
        private void GetAssetA2ForQuery()
        {
            MsQuery msq = new MsQuery();
            msq.strquery += " and 1=1 ";
            DataTable dt = ((DataSet)new BLLasset_a2().Getasset_a2ByQuery(msq).data).Tables[0];
        }
        /// <summary>
        /// 品牌配置
        /// </summary>
        private void GetAssetA3()
        {
            MsQuery msqa3 = new MsQuery();
            msqa3.strquery += " and (ASSET_A3_ISDEL='1' or ASSET_A3_ISDEL is null) ";
            DataTable a3dt = ((DataSet)new BLLasset_a3().Getasset_a3ByQuery(msqa3).data).Tables[0];
            DataSource.Add("DataSource", JArray.FromObject(a3dt));
        }
        /// <summary>
        /// 型号配置
        /// </summary>
        private void GetAssetA4()
        {
            DataTable a4dt = GetAssetA4("");
            DataSource.Add("DataSource", JArray.FromObject(a4dt));
        }
        /// <summary>
        /// 型号配置
        /// </summary>
        private DataTable GetAssetA4(string a3id)
        {
            MsQuery msqa4 = new MsQuery();
            msqa4.strquery += " and (ASSET_A4_ISDEL='1' or ASSET_A4_ISDEL is null) ";
            if (a3id != "")
            {
                msqa4.strquery += " and ASSET_A4_30='" + a3id + "' ";
            }
            DataTable a4dt = ((DataSet)new BLLasset_a4().Getasset_a4ByQuery(msqa4).data).Tables[0];
            a4dt.Columns.Add("disabled");
            MsQuery msqa3 = new MsQuery();
            msqa3.strquery += " and (ASSET_A3_ISDEL='1' or ASSET_A3_ISDEL is null) ";
            if (a3id != "")
            {
                msqa3.strquery += " and ASSET_A3_AUTOID='" + a3id + "' ";
            }
            DataTable a3dt = ((DataSet)new BLLasset_a3().Getasset_a3ByQuery(msqa3).data).Tables[0];

            //foreach (DataRow item in a4dt.Rows)
            //{
            //    item["disabled"] = "0";
            //}
            foreach (DataRow item in a3dt.Rows)
            {
                DataRow dr = a4dt.NewRow();
                dr["ASSET_A4_10"] = item["ASSET_A3_10"].ToString();
                dr["ASSET_A4_AUTOID"] = item["ASSET_A3_AUTOID"].ToString();
                dr["disabled"] = "1";
                a4dt.Rows.Add(dr);
            }
            DataSource.Add("DataSource", JArray.FromObject(a4dt));
            return a4dt;
        }
        /// <summary>
        /// 存放地址配置
        /// </summary>
        private void GetAssetA5()
        {
            MsQuery msqa5 = new MsQuery();
            msqa5.strquery += " and (ASSET_A5_ISDEL='1' or ASSET_A5_ISDEL is null) ";
            DataTable a5dt = ((DataSet)new BLLasset_a5().Getasset_a5ByQuery(msqa5).data).Tables[0];
            DataSource.Add("DataSource", JArray.FromObject(a5dt));
        }
        /// <summary>
        /// 部门
        /// </summary>
        private void GetSystem2()
        {
            MsQuery msq = new MsQuery(" and 1=1");
            DataTable dt = ((DataSet)(new BLLsystem_2().Getsystem_2ByQuery(msq).data)).Tables[0];
            DataSource.Add("DataSource", JArray.FromObject(dt));
        }

        /// <summary>
        /// 得到资产列头
        /// </summary>
        /// <returns></returns>
        private List<Mssys_asset_a1> GetSysAssetA2()
        {
            List<Mssys_asset_a1> listsysa1 = new List<Mssys_asset_a1>();
            MsQuery msq = new MsQuery();
            msq.strquery += " and SYS_ASSET_A1_40='1' AND SYS_ASSET_A1_120='1'";//有效性 和 是否显示
            msq.typecode1 = "asset";//列表标识
            msq.obj1 = GetSessionUser();
            listsysa1 = new BLLsys_asset_a1().Getsys_asset_a1MsByQuery(msq);
            return listsysa1;
        }

        #endregion


        /// <summary>
        /// 上传验证数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("CheckData")]
        public async Task<string> CheckData([FromBody] dynamic data)
        {
            var res = await Task.Run<string>(() =>
            {
                JObject postdata = JObject.FromObject(data.data);
                //excel数据[{sysA1_160:val}]
                JArray ExcelData = JArray.FromObject(postdata["data"]);
                string batch = postdata["batch"].ToString();
                List<MsReturned> msr = new List<MsReturned>();
                //验证数据
                msr = new BLLasset_a1().CheckData(ExcelData, batch);

                JArray json = new JArray();

                foreach (var item in msr)
                {
                    JObject jobj = new JObject();
                    jobj.Add("id", item.strMsId);//标识 ASSET_A1_30 系统编号
                    jobj.Add("includes", item.MsRbool);//是否存在 判断更新和新增
                    jobj.Add("msg", item.strMS==""?"1": item.strMS);//消息
                    jobj.Add("errCol", (JArray)item.obj2);//错误的列
                    jobj.Add("assign", (JObject)item.obj1);//扩展 对于字典 中文=>值 JObject 
                    json.Add(jobj);
                }

                return json.ToString();
            });
            return res;
        }
    }
}